<template>
  <!-- 医生-我的用户 -->
  <div class="my-user-box">
    <div class="l-panel">
      <template>
        <div>
          <el-form :inline="true" class="demo-form-inline" size="small">
            <el-form-item label="">
              <el-input v-model="searchParams.searchKey" placeholder="患者姓名/手机号"></el-input>
            </el-form-item>
            <el-form-item>
              <el-date-picker
                  size="small"
                  v-model="searchParams.date"
                  type="datetimerange"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始申请日期"
                  end-placeholder="结束申请日期"
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item label="">
              <el-select v-model="searchParams.status" placeholder="处理状态">
                <el-option label="全部" value=""></el-option>
                <el-option v-for="item in handleStatusList" :key="item.id" :label="item.name" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="getList()"
              >查询</el-button
              >
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="applyConsult"
              >会诊申请+</el-button
              >
            </el-form-item>
          </el-form>
        </div>
        <yx-table
          :is-fit="false"
          :table-data="tableData"
          :columns="columns"
          :page-obj="pageObj"
          :loading="loading"
          :tableHeightDefault="500"
          :isPaginationShow="false"
        >
          <template slot="operate" slot-scope="scope">
            <div class="operate-btn">
                <el-button
                  v-if="getBtnPermission(scope).detail"
                  style="color: #006DB8;"
                  size="small"
                  type="text"
                  @click="viewDetail(scope)"
                >
                  查看详情
                </el-button>
                <el-button
                    v-if="getBtnPermission(scope).lunchConsult"
                  style="color: #006DB8;"
                  size="small"
                  type="text"
                  @click="lunchConsult(scope)"
                >
                  发起会诊
                </el-button>
                <el-button
                  v-if="getBtnPermission(scope).insertConsult"
                  style="color: #006DB8;"
                  size="small"
                  type="text"
                  @click="insertConsult(scope)"
                >
                  加入会诊
                </el-button>
                <el-button
                    v-if="getBtnPermission(scope).viewConsult"
                  style="color: #006DB8;"
                  size="small"
                  type="text"
                  @click="viewConsult(scope)"
                >
                  查看会诊单
                </el-button>
                <el-button
                    v-if="getBtnPermission(scope).passConsult"
                  style="color: #006DB8;"
                  size="small"
                  type="text"
                  @click="passConsult(scope)"
                >
                  通过审核
                </el-button>
                <el-button
                  v-if="getBtnPermission(scope).rejectConsult"
                  style="color: #006DB8;"
                  size="small"
                  type="text"
                  @click="rejectConsult(scope)"
                >
                  拒绝会诊
                </el-button>
            </div>
          </template>
        </yx-table>
      </template>
    </div>
    <!-- 发送消息弹窗 -->
    <el-dialog :title="'发送消息'" :visible.sync="mesVisible">
      <div>
        <el-form :model="messageForm" ref="messageForm" :rules="rules">
          <el-form-item prop="message">
            <el-input
              type="textarea"
              :rows="4"
              placeholder="请输入内容"
              v-model="messageForm.message"
            >
            </el-input>
          </el-form-item>
        </el-form>
      </div>
      <div class="send-message-btn" slot="footer">
        <el-button size="small" @click="mesVisible = false">取消</el-button>
        <el-button type="primary" size="small" @click="saveMessage"
          >保存</el-button
        >
      </div>
    </el-dialog>

    <!-- 患者聊天记录 -->
    <el-dialog
      class="dialog-frame"
      title="聊天记录"
      width="800"
      :visible.sync="chatRecordDialog"
      @close="chatRecordDialog = false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-button type="primary" @click="openVideoRecord">视频记录</el-button>
      <el-table
        class="l-table"
        :data="recordList"
        border
        max-height="480"
        highlight-current-row
      >
        <el-table-column prop="name" label="时间">
          <template slot-scope="scope">
            <span>{{ scope.row.msgDate || "-" }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="角色">
          <template slot-scope="scope">
            <span>{{ scope.row.msgUserName }} </span>
          </template>
        </el-table-column>
        <el-table-column prop="size" label="内容">
          <template slot-scope="scope">
            <viewer v-if="isUrl(scope.row.msgText)">
              <img :src="scope.row.msgText" width="100" title="点击预览" />
            </viewer>
            <span v-else>{{ scope.row.msgText }}</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="text-align:center;margin:15px 25px;"
        @current-change="changeRecordListCurrent"
        :current-page="recordPage.current"
        :page-size="recordPage.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="recordPage.total"
        @size-change="handleSizeChange"
        :page-sizes="[10, 20, 50]"
      >
      </el-pagination>
    </el-dialog>
    <!-- 会诊 -->
    <el-dialog
      title="会诊"
      width="1000"
      :visible.sync="dialogStart"
      v-if="dialogStart"
      @close="dialogStart = false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <StartConsult />
    </el-dialog>
    <!-- 拒绝会诊 -->
    <el-dialog
        title="拒绝原因"
        width="200"
        :visible.sync="dialogReject"
        v-if="dialogReject"
        @close="dialogReject = false"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
    >
      <el-input
          type="textarea"
          :rows="5"
          v-model="rejectReason"
          placeholder="请输入拒绝原因"
      ></el-input>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogReject = false">取 消</el-button>
        <el-button size="small" type="primary" @click="submitReject">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 查看病历组件 -->
    <case-history ref="caseHistory"></case-history>
    <viewConsult ref="viewConsultRef"/>
<!--    <MeetingRoomDialog :visible="waitDialog" :roomList="waitList" />-->
  </div>
</template>

<script>
import yxTable from "@/components/yxtable/yx-table";
import caseHistory from "@/components/case-history";
import viewConsult from "@/components/viewConsult";
import StartConsult from "./startConsult.vue";
import apply from "./apply.vue";
import detail from "./detail.vue";
import { isUrl } from "@/utils";
import MeetingRoomDialog from "./MeetingRoomDialog.vue";
import CallDialog from "./CallDialog.vue";
export default {
  components: {
    CallDialog,
    MeetingRoomDialog,
    yxTable,
    caseHistory,
    apply,
    detail,
    viewConsult,
    StartConsult
  },
  data() {
    return {
      viewCaseVisible: false,
      searchParams: {
        searchKey: '',
        status: '',
        date: []
      },
      handleStatusList: [
        {
          id: '0',
          name: '已取消'
        },
        {
          id: '1',
          name: '待审核'
        },
        {
          id: '2',
          name: '审核通过'
        },
        {
          id: '3',
          name: '会诊中'
        },
        {
          id: '4',
          name: '已结束'
        },
      ],
      columns: [
        {
          // TODO
          label: '房间号',
          prop: 'id',
          width: 100,
        },
        {
          // TODO
          label: '患者姓名',
          prop: 'inquiryPatientName',
          width: 100,
        },
        {
          // TODO
          label: '会诊医生',
          prop: 'doctorName',
          width: 100,
        },
        {
          // TODO
          label: '会诊专家',
          prop: 'expertDoctorName',
          width: 100,
        },
        // TODO
        {
          label: '患者联系电话',
          prop: 'inquiryPatientPhone',
          width: 140,
        },
        {
          // TODO
          label: '会诊医院',
          prop: 'hospitalName',
          width: 100,
        },
        {
          label: '备注',
          prop: 'remarks',
        },
        {
          label: '处理状态',
          prop: 'statusName',
          width: 100,
        },
        {
          label: '拒绝原因',
          prop: 'refuseReason',
          width: 100,
        },
        {
          label: '申请时间',
          prop: 'createTime',
          width: 100,
        },
        {
          label: '结束时间',
          prop: 'rcsEndTime',
          width: 100,
        },
        { label: "操作", slot: "operate", fixed: "right", width: 200 }
      ],
      doctorInfo: {
        doctorJobTitle: ''
      },
      loading: false,
      pageObj: {
        size: 10,
        total: 0,
        currentPage: 1,
      },
      tableData: [],
      mesVisible: false,
      messageForm: {
        message: ""
      },
      rules: {
        message: [{ required: true, message: "数量不能为空", trigger: "blur" }]
      },
      caseInfo: {},
      idCard: "",
      userId: null,
      chatRecordDialog: false, //聊天记录弹框
      patientMsg: {}, //患者消息列表
      recordPage: {
        //聊天记录分页
        total: 0,
        current: 1,
        size: 10
      },
      recordList: [], //聊天记录列表
      dialogVideoRecord: false,
      /**
       * 审批
       */
      currentRecordItem: {},
      dialogReject: false,
      rejectReason: "",
      /**
       * 开始会诊
       */
      dialogStart: false,
      /**
       * 待会诊列表
       */
      waitList: [],
      waitDialog: false,
      /**
       * 待会诊2
       */
      showCallDialog: false
    };
  },
  created() {
    this.loading = true
    // 获取医生
    this.$ajax.getInquiryDoctorInfo({
      webToken: this.$authInfo.webToken(),
      id: this.$authInfo.getUser().id
    }).then(res => {
      this.doctorInfo = res.data
    }).catch(() => {
      this.loading = false
    })
    this.getList()
  },
  methods: {
    async handleAcceptCall() {
      let current = this.waitList[this.waitList.length - 1]
      this.joinChannel(current)
    },
    handleRejectCall() {
      this.showCallDialog = false
      this.$message({
        type: 'info',
        message: '您已拒绝加入会议'
      })
      this.waitList = []
    },
    joinChannel(data) {
      // 加入会诊室
      this.$setWsRemote.send(5, {
        roomId: data.roomId,
        packageType: 3,
        timestamp: new Date().getTime()
      });
      this.$router.push({
        path: '/startConsult',
        query: {
          id: data.roomId
        }
      })
    },
    isUrl,
    // 发送消息
    sendMes(e) {
      this.userId = e.userId;
      this.mesVisible = true;
    },
    // 查看病历
    checkCase(e) {
      this.$nextTick(() => {
        if (this.$global.platform("lj")) {
          this.$refs.caseHistory.onOpen("his", e);
        } else {
          if (this.$global.isNewCase) {
            this.$refs.caseHistory.onOpen("ca", e);
          } else {
            this.$refs.caseHistory.onOpen("normal", {
              caseInfo: e,
              idCard: e.patientIdcard
            });
          }
        }
      });
    },
    saveMessage() {
      let para = {
        webToken: this.$authInfo.webToken(),
        noticeContent: this.messageForm.message,
        userId: this.userId
      };
      this.$ajax
        .sendNewsMysubscriber(para)
        .then(res => {
          this.mesVisible = false;
          this.$message({
            message: res.msg,
            type: "success"
          });
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    pageTurning(currentPage) {
      this.pageObj.currentPage = currentPage;
      this.getList();
    },
    sizeChange(size) {
      this.pageObj.size = size;
      this.getList();
    },
    getList() {
      this.loading = true;
      let params = {
        searchKey: this.searchParams.searchKey,
        status: this.searchParams.status,
      };

      if (this.searchParams.date && this.searchParams.date.length) {
        params.startTime = this.searchParams.date[0];
        params.endTime = this.searchParams.date[1];
      }

      this.$ajax
        .getMyConsultationList(params)
        .then(res => {
          console.log(res)
          this.tableData = res.data
          this.loading = false;
          this.tableData.forEach(item => {
            let find = this.handleStatusList.find(i => i.id == item.status);
            item.statusName = find ? find.name : item.status;
            let expertDoctorName = item.expertDoctorList.map(item => item.expertDoctorName).join(',')
            item.expertDoctorName = expertDoctorName
          })
          console.log('this.tableData',)
        }).finally(() => {
          this.loading = false;
        });
    },
    handleSizeChange(val) {
      this.recordPage.size = val;
      this.getRecordList();
      return true
    },
    getRecordList({ page } = {}) {
      // 诊断规范
      page && (this.recordPage.current = page);
      let para = {
        webToken: this.$authInfo.webToken(),
        current: this.recordPage.current,
        size: this.recordPage.size,
        patientId: this.patientMsg.userId,
        userSource: this.patientMsg.userSource
      };
      this.$ajax
        .getChatRecord(para)
        .then(res => {
          this.recordList = res.data.list.map(item => {
            return {
              ...item,
              status: item.status || 1
            }
          });
          this.recordPage.total = res.data.total;
          this.recordPage.page = res.data.pages;
        })
        .catch(err => {
          this.$message({
            message: err.msg,
            type: "error"
          });
        });
    },
    changeRecordListCurrent(val) {
      //诊断规范分页
      this.recordPage.current = val;
      this.getRecordList();
      return true
    },
    openVideoRecord() {
      this.dialogVideoRecord = true;
    },
    applyConsult() {
      this.$router.push({
        path: '/remoteConsult/apply'
      })
    },
    backConsult() {
    },
    viewDetail(scope) {
      console.log('row',scope)
      this.$router.push({
        path: '/remoteConsult/detail?id=' + scope.scope.id
      })
    },
    lunchConsult({ scope }) {
      this.$router.push({
        path: "/startConsult",
        query: {
          id: scope.id,
        }
      });
    },
    insertConsult({ scope }) {
      this.$router.push({
        path: "/startConsult",
        query: {
          id: scope.id
        }
      });
    },
    viewConsult({ scope }) {
      // TODO 增加签名
      this.$refs.viewConsultRef.open(scope.pdfUrl)
    },
    passConsult({ scope }){
      this.$confirm("确认通过审核？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.$ajax.auditConsultation({
            "isPass": 0,
            "rcsLogId": scope.id
          }).then(res => {
            this.$message({
              type: "success",
              message: "审核成功!"
            });
            this.getList()
          })
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消"
          });
        });
    },
    rejectConsult(scope) {
      console.log('row',scope.scope)
      this.currentRecordItem = scope.scope
      this.dialogReject = true;
    },
    submitReject() {
      console.log(this.rejectReason, "==1-");
      if (!this.rejectReason.trim()) {
        this.$message({
          type: "warning",
          message: "请输入拒绝原因"
        });
        return;
      } else {
        console.log('currentRecordItem', this.currentRecordItem)
        this.$ajax.auditConsultation({
          "isPass": 1,
          "rcsLogId": this.currentRecordItem.id,
          rejectReason: this.rejectReason.trim()
        }).then(res => {
          this.dialogReject = false
          this.$message({
            type: "success",
            message: "审核成功!"
          });
          this.getList()
        })
      }
    },

    /**
     * 判断操作状态
     */
    getBtnPermission(scope) {
      let { status, expertDoctorList: [] } = scope.scope
      let map = {
        // 详情
        detail: false,
        // 发起会诊
        lunchConsult: false,
        // 查看会诊单
        viewConsult: false,
        // 通过审核
        passConsult: false,
        // 拒绝会诊
        rejectConsult: false,
        // 进入会诊
        insertConsult: false
      }
      // 状态不存在
      const find = this.handleStatusList.find(item => item.id == status)
      if (!find) {
        return map
      }
      // 	0已取消 1待审核 2审核通过 3会诊中 4已结束
      // 当前角色
      const adminUserInfoStr = this.$getStore('adminUserInfo')
      if (!adminUserInfoStr) return map
      let adminUserInfo = JSON.parse(adminUserInfoStr)
      // 专家 isExpert
      let isExpert = adminUserInfo.type === 'D-E'
      if (isExpert) {
        // 0已取消（已拒绝） 1待审核 2审核通过（待会诊） 3会诊中 4已结束
        // 根据状态判断
        if (status == '0') {
          map.detail = true
          return map
        }
        if (status == '1') {
          map.detail = true
          map.passConsult = true
          map.rejectConsult = true
          return map
        }
        if (status == '2') {
          map.detail = true
          map.lunchConsult = true
          return map
        }
        if (status == '3') {
          map.detail = true
          map.insertConsult = true
          return map
        }
        if (status == '4') {
          map.detail = true
          map.viewConsult = true
          return map
        }
      } else {
        // 根据状态判断
        // 0已取消（已拒绝） 1待审核 2审核通过（待会诊） 3会诊中 4已结束
        if (status == '0') {
          map.detail = true
          return map
        }
        if (status == '1') {
          return map
        }
        if (status == '2') {
          map.detail = true
          map.lunchConsult = true
          return map
        }
        if (status == '3') {
          map.detail = true
          map.insertConsult = true
          return map
        }
        if (status == '4') {
          map.detail = true
          map.viewConsult = true
          return map
        }
      }
      return map
    },
  },
};
</script>

<style lang="scss">

.my-user-box {
  .l-panel {
    width: 100%;
    padding: 30px;
  }
}

.send-message-btn {
  text-align: center;
}

.dialog-frame {
  .el-dialog {
    width: 800px !important;
    max-width: 900px !important;
  }
}
</style>
